from log import log

def Select(fields, table, where={}):
  global database
  results = []
  for row in FindRows(database[table], where):
    if fields == "*":
      d = dict(database[table][row])
    else:
      d = {}
      rowdict = database[table][row]
      for k in fields:
        d[k] = rowdict.get(k, None)
    results.append(d)

  return results

def Update(table, values, where=None):
  global database
  for row in FindRows(database[table], where):
    for k, v in values.iteritems():
      database[table][row][k] = v

  sql = "update %s set " % table
  list = []
  for k, v in values.iteritems():
    list.append("%s=%s" % (k, SqlEncode(v)))
  sql += ",".join(list)

  if where:
    list = []
    sql += " where "
    for k, v in where.iteritems():
      list.append("%s=%s" % (k, SqlEncode(v)))
    sql += " and ".join(list)

  print sql

def Insert(table, keysvalues):
  global database
  database[table].append(dict(keysvalues))

  sql = "insert into %s (" % table
  keys = []
  values = []
  for k, v in keysvalues.iteritems():
    keys.append(k)
    values.append(SqlEncode(v))
  sql += ",".join(keys)
  sql += ") values ("
  sql += ", ".join(values)
  sql += ")"
  print sql

def RowMatches(row, where):
  for k, v in where.iteritems():
    if row.get(k, None) != v:
      return False
  return True

def FindRows(table, where):
  """Return a list of matching indices."""
  i = 0
  results = []
  while i < len(table):
    if RowMatches(table[i], where):
      results.append(i)
    i += 1
  return results

def Remove(table, where):
  global database
  rows = FindRows(database[table], where)
  rows.sort()
  rows.reverse()
  for row in rows:
    del database[table][row]

  sql = "remove from %s where " % table
  list = []
  for k, v in where.iteritems():
    list.append("%s=%s" % (k, SqlEncode(v)))
  sql += list.join(" and ")

  print sql

